<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              治安重点地区：<el-input placeholder="请输入内容" v-model="selectForm.importantArea" class="dzy-custom-input"></el-input>
            </div>
            <div>
              治安突出问题：
              <el-select v-model="selectForm.securityProminentProblem" clearable placeholder="请选择">
                <el-option v-for="(item,index) in problemOption" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              涉及区域类型：
              <el-select v-model="selectForm.areaType" clearable placeholder="请选择">
                <el-option v-for="(item,index) in areaTypeOptions" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              涉及区域范围：<el-input placeholder="请输入内容" v-model="selectForm.areaRegion" class="dzy-custom-input"></el-input>
            </div>
            <div>
              效果评估：
              <el-select v-model="selectForm.effectEvaluation" placeholder="请选择" clearable>
                <el-option v-for="(item,index) in effectOptions" :key="index" :label="item.name" :value="item.code"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" class="custom-dialog_style_twoLine" :before-close="cancel" :close-on-click-modal="false">
            <el-form :model="formData"
                     :rules="rules"
                     ref="formData"
                     :disabled="showOnly"
                     label-width="50%">
              <el-form-item label="治安重点地区：" prop="importantArea" label-width="49%">
                <el-input v-model="formData.importantArea" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="治安突出问题：" prop="securityProminentProblem" label-width="49%">
                <el-select v-model="formData.securityProminentProblem" placeholder="请选择" clearable>
                  <el-option v-for="(item,index) in problemOption" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="涉及区域类型：" label-width="49%">
                <el-select v-model="formData.areaType" placeholder="请选择" clearable>
                  <el-option v-for="(item,index) in areaTypeOptions" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="涉及区域范围：" prop="areaRegion" label-width="49%">
                <el-input v-model="formData.areaRegion" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="整治牵头单位：" label-width="49%">
                <el-input v-model="formData.renovatingLeadUnit" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="整治参与单位：" label-width="49%">
                <el-input v-model="formData.renovatingJoinUnit" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="整治牵头单位负责人姓名：" label-width="49%">
                <el-input v-model="formData.principalName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="整治牵头单位负责人联系方式：" prop="principalPhone" label-width="49%">
                <el-input v-model="formData.principalPhone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="整改时限：" label-width="49%">
                <el-input v-model="formData.timeLimit" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="整治期间破获刑事案件数：" label-width="49%">
                <el-input v-model="formData.criminalNum" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="整治期间查出治安案件数：" label-width="49%">
                <el-input v-model="formData.securityNum" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="效果评估：" label-width="49%">
                <el-select v-model="formData.effectEvaluation" placeholder="请选择" clearable>
                  <el-option v-for="(item,index) in effectOptions" :key="index" :label="item.name" :value="item.code"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="整治情况：" label-width="49%" class="custom-textarea-container">
                <el-input type="textarea" v-model="formData.remediation"></el-input>
              </el-form-item>
              <el-form-item label="" label-width="49%">
              </el-form-item>
              <el-form-item label="选择经纬度：" class="custom-longla-container">
                <el-input v-model="formData.longitude" :disabled="true" placeholder="经度" ></el-input>
                <el-input v-model="formData.latitude" :disabled="true" placeholder="纬度" ></el-input>
                <el-button type="text" @click="openSimpleMap" style="color: red;">[ 选择 ]</el-button>
              </el-form-item>
              <el-form-item label="" label-width="49%">
              </el-form-item>
              <el-form-item label="街道/社区/网格：" label-width="49%">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="treeData"
                    filterable
                    :props="gridIdProps"
                    v-model="formData.gridIdArr"
                    clearable
                    change-on-select>
                  </el-cascader>
                </div>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="isfooterBtnShow">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save('formData')">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog class="dialog-body-mini" :visible.sync="showMap" title="选择经纬度" width="70%" top="8vh" :before-close="mapCancel">
            <edit-map v-if="showMap" :mode="mapMode" @appMapCallback="appMapCallback" :target="mapTarget" ></edit-map>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import EditMap from '@/components/EditMap'
import {getAllRegion} from '@/utils/region'
import {validatePhone} from '@/utils/validate'
import {createMapLocation} from '@/http/AppApi'
import {getUserGridTree} from '@/utils/SessionDataUtil'
import {getDictDataOption} from '@/utils/getDictDataOption'
import {getImportantArea, createImportantArea, updateImportantArea, delImportantArea} from '@/http/PublicSecurityAppApi'
export default {
  data () {
    return {
      dialogFormVisible: false,
      isfooterBtnShow: true,
      mapHackReset: false,
      showMap: false,
      mapMode: 'simple',
      mapTarget: {},
      treeData: [],
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      tableColumns: [
        { prop: 'importantArea', label: '治安重点地区' },
        { prop: 'securityProminentProblem', label: '治安突出问题', formatter: this.problemFormatter },
        { prop: 'areaType', label: '涉及区域类型', formatter: this.areaTypeFormatter },
        { prop: 'areaRegion', label: '涉及区域范围' },
        { prop: 'renovatingLeadUnit', label: '整治牵头单位' },
        { prop: 'renovatingJoinUnit', label: '整治参与单位' }
      ],
      tableDada: [],
      selectForm: {},
      formData: {},
      options: [],
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      rules: {
        importantArea: [
          { required: true, message: '请输入治安重点地区：', trigger: 'blur' }
        ],
        securityProminentProblem: [
          { required: true, message: '请选择突出问题', trigger: 'blur' }
        ],
        areaRegion: [
          { required: true, message: '请输入涉及区域范围', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '请选择经纬度', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '请选择经纬度', trigger: 'blur' }
        ],
        principalPhone: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        gridIdArr: [
          { required: true, message: '请选择网格', trigger: 'blur' }
        ]
      },
      problemOption: [],
      areaTypeOptions: [],
      effectOptions: []
    }
  },
  components: {
    EditMap,
    AppTree,
    BtnGroup,
    AppTable
  },
  mounted () {
    this.problemOption = getDictDataOption('治安突出问题')
    this.areaTypeOptions = getDictDataOption('涉及区域类型')
    this.effectOptions = getDictDataOption('效果评估')
    this.getTreeData()
    this.getTableData()
  },
  methods: {
    problemFormatter (row, column) {
      let problemOption = getDictDataOption('治安突出问题')
      let resProblem = ''
      for (let i = 0; i < problemOption.length; i++) {
        if (problemOption[i].code === row.securityProminentProblem) {
          resProblem = problemOption[i].name
          break
        }
      }
      return resProblem
    },
    areaTypeFormatter (row, column) {
      let areaTypeOption = getDictDataOption('涉及区域类型')
      let resAreaType = ''
      for (let i = 0; i < areaTypeOption.length; i++) {
        if (areaTypeOption[i].code === row.areaType) {
          resAreaType = areaTypeOption[i].name
          break
        }
      }
      return resAreaType
    },
    getTreeData () {
      let data = getUserGridTree()
      if (data && data instanceof Array) {
        this.treeData = data
      }
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          this.$alert('请填写正确表单格式', '', {
            confirmButtonText: '确定'
          })
          return ''
        } else {
          if (this.formData.gridIdArr && this.formData.gridIdArr !== 0) {
            let index = this.formData.gridIdArr.length - 1
            let data = {}
            data.id = this.formData.gridIdArr[index]
            data.items = this.treeData
            data.isGetAllId = true
            this.formData.allGridId = getAllRegion(data)
          } else {
            this.formData.allGridId = ''
          }
          if (this.formData.id) {
            updateImportantArea(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '修改失败'
                })
                return ''
              }
            })
          } else {
            createImportantArea(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '添加失败'
                })
                return ''
              }
            })
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delImportantArea(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: '删除失败'
                })
                return ''
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
    },
    getTableData (param) {
      getImportantArea(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        this.isfooterBtnShow = callbackData.btnType !== 'get'
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.gridIdArr) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.$set(this.formData, 'gridIdArr', arr)
          } else {
            this.formData = {}
          }
        } else {
          let obj = {}
          obj = JSON.stringify(callbackData.rows[0])
          this.formData = JSON.parse(obj)
          let regionData = {}
          regionData.id = this.formData.gridId
          regionData.items = this.treeData
          let gridIdArr = getAllRegion(regionData)
          this.$set(this.formData, 'gridIdArr', gridIdArr)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else if (rows.length === 0) {
        this.currentSelectedData = []
      }
    },
    appTreeClick (data) {
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.treeData
      let gridIdArr = getAllRegion(gridData)
      this.$set(this.formData, 'gridIdArr', gridIdArr)
      this.selectForm.gridId = data.id
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    searchHandleClick () {
      this.selectForm.offset = 0
      this.getTableData(this.selectForm)
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        let mapLocation = {}
        mapLocation.targetId = appMapInfo.target.targetId
        mapLocation.targetType = appMapInfo.target.targetType
        if (appMapInfo.clearStatus) {
          mapLocation.clearStatus = appMapInfo.clearStatus
        }
        if (appMapInfo.markPosition) {
          mapLocation.longitude = appMapInfo.markPosition.lng
          mapLocation.latitude = appMapInfo.markPosition.lat
        }
        if (appMapInfo.polyPathArr) {
          mapLocation.mapArea = appMapInfo.polyPathArr
          mapLocation.mapColor = appMapInfo.polyColor
          createMapLocation(mapLocation).then(resp => {
            if (resp.code && resp.code === '200') {
              console.log('保存成功')
            }
          })
        }
      }
      if (appMapInfo.lnglat) {
        this.formData.longitude = appMapInfo.lnglat.lng
        this.formData.latitude = appMapInfo.lnglat.lat
      }
      this.mapCancel()
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    },
    isObjEmpty (obj) {
      for (var key in obj) {
        return false
      }
      return true
    }
  }
}
</script>
